﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessComponents;
using BusinessComponents.Managers;
using WaterfrontLodge.Models;
using System.Web.Security;
using System.Web.Routing;
using WaterfrontLodge.Validators;

namespace WaterfrontLodge.Controllers
{
    public class ReservationController : Controller
    {
        IReservationMgr resMgr = ManagerFactory.ReservationMgr;
        
        //
        // GET: /Reservation/

        [Authorize]
        [OutputCache(Duration = 1, VaryByParam = "None")] 
        public ActionResult Index()
        {
            Guid userId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            return View(resMgr.listReservationByUserId(userId));
        }

        //
        // GET: /Reservation/Details/5
        [Authorize]
        public ActionResult Details(string id)
        {
            ReservationMaster res = resMgr.getReservationInfo(id);

            if (res != null)
            {
                return View(res);
            }
            else
            {
                TempData["Message"] = "Sorry, no record found.";
                return RedirectToAction("Search");
            }
        }

        //
        // GET: /Reservation/Create
        [OutputCache(Duration = 1, VaryByParam = "None")]
        [Authorize]
        public ActionResult Create()
        {
            try{
                ReservationTransferObject rto = new ReservationTransferObject();
                Session["RESERVATION_TRANSFER_OBJECT"] = rto;

                //ModelState

                return View(rto.CurrView, rto.Master);
            }
            catch (Exception ex)
            {
                Session["RESERVATION_TRANSFER_OBJECT"] = null;
                return View("Error", new HandleErrorInfo(ex, "ReservationController", "Create"));
            }
           
        } 

        //
        // POST: /Reservation/Create

        [HttpPost]
        [Authorize]
        public ActionResult Create(string btnSubmit, ReservationMaster master, FormCollection collection)
        {
            try
            {
                if (btnSubmit == "Cancel")
                {
                    Session["RESERVATION_TRANSFER_OBJECT"] = null;
                    return RedirectToAction("Index");
                }
                else
                {
                    ReservationTransferObject rto = Session["RESERVATION_TRANSFER_OBJECT"] as ReservationTransferObject;

                    try
                    {
                        if (rto.CurrView == "Create")
                        {
                            ReservationValidator.chkReservationPeriod(master);

                            rto.Master.StartDate = master.StartDate;
                            rto.Master.EndDate = master.EndDate;
                            rto.Master.DayCount = master.DayCount;
                            rto.updateView();
                        }
                        else if (rto.CurrView == "CreateStep1")
                        {
                            master.DayCount = rto.Master.DayCount;
                            ReservationValidator.chkReservationRoom(master);

                            rto.Master.TypeCode = master.TypeCode;
                            rto.Master.RoomTypeDesc = master.RoomTypeDesc;
                            rto.Master.RoomCount = master.RoomCount;
                            rto.Master.NoOfPax = master.NoOfPax;
                            rto.Master.TotalCost = master.TotalCost;
                            rto.updateView();
                        }
                        else if (rto.CurrView == "CreateStep2")
                        {
                            ReservationValidator.chkReservationRemarks(master);

                            rto.Master.Remarks = master.Remarks;

                            bool done = ManagerFactory.ReservationMgr.createReservation(rto.Master);

                            if (done)
                            {
                                rto.updateView();
                                Session["RESERVATION_TRANSFER_OBJECT"] = null;
                                return RedirectToAction("Details", "Reservation", new { id = rto.Master.ReservationId });
                            }
                            else
                            {
                                TempData["Message"] = "Sorry, no suitable room available for booking at this moment.";
                            }
                        }

                    }
                    catch (ValidationException vex)
                    {
                        ModelState.AddModelError(vex.ID, vex.Message);
                    }

                    return View(rto.CurrView, rto.Master);
                    //return RedirectToAction("Create");
                }
            }
            catch (Exception ex)
            {
                Session["RESERVATION_TRANSFER_OBJECT"] = null;
                return View("Error", new HandleErrorInfo(ex, "ReservationController", "Create"));
            }
        }


        //
        // GET: /Reservation/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Reservation/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Reservation/Delete/5
        [Authorize]
        public ActionResult Delete(string id)
        {
            bool canDelete = false;

            if(User.IsInRole("admin")){
                canDelete = true;
            }
            else if(User.Identity.IsAuthenticated){
                Guid userId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                canDelete = ReservationValidator.chkIsReservationOwner(id, userId);
            }

            if (canDelete)
            {
                resMgr.cancelReservation(id);
                return RedirectToAction("Details", "Reservation", new { id = id });
            }
            else
            {
                return RedirectToAction("LogOn");
            }
        }

        [Authorize(Roles="admin")]
        public ActionResult Search()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Search(string query)
        {
            if (Request.IsAjaxRequest())
            {
                string q = ("" + query).Trim().ToUpper();
                return View("SearchResult", ManagerFactory.ReservationMgr.listReservationByPattern(q));
                //return RedirectToAction("Details", "Reservation", new { id = query });
            }
            else
            {
                return View(new List<ReservationMaster>());
            }
        }

        [OutputCache(Duration = 300, VaryByParam = "q")]
        [Authorize(Roles = "admin")]
        public string ReservationIdList(string q)
        {
            string resList = "";
            string query = ("" + q).Trim().ToUpper();
            IEnumerable<ReservationMaster> list = ManagerFactory.ReservationMgr.listReservationByPattern(query);

            int limit = 5;
            foreach(var m in list){
                if (limit > 0)
                {
                    resList += m.ReservationId + "\n";
                    limit--;
                }
                else
                {
                    break;
                }
            }

            return resList;
        }

        //
        // POST: /Reservation/Delete/5

        [HttpPost]
        [Authorize]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

    public class ReservationTransferObject
    {

        public ReservationTransferObject()
        {
            Master = new ReservationMaster();

            Master.UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            Master.StartDate = DateTime.Now.AddDays(1);
            Master.EndDate = DateTime.Now.AddDays(1);
            Master.TypeCode = 1;
            Master.NoOfPax = 1;
            Master.RoomCount = 1;
            CurrView = "Create";
        }

        public ReservationMaster Master
        {
            get;
            set;
        }

        public string CurrView
        {
            get;
            set;
        }

        public void updateView()
        {
            switch (CurrView)
            {
                case "Create":
                    CurrView = "CreateStep1"; 
                    break;
                case "CreateStep1":
                    CurrView = "CreateStep2"; 
                    break;
                case "CreateStep2":
                    CurrView = "Details"; 
                    break;
                default:
                    CurrView = "Create"; 
                    break;
            }
        }

    }
}
